package com.bitters.fileupload.controller;

import com.bitters.fileupload.util.FileUtil;
import com.bitters.fileupload.util.HttpContextUtil;
import com.bitters.fileupload.entity.FileProgressEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Calendar;

/**
 * @author thomashe
 * @date 2022/5/30
 **/
@Controller
@RequestMapping("/api/file")
public class FileUploadController {
    final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    private final String resourcePath = "F:/";

    @ResponseBody
    @PostMapping("/upload")
    public String upload(@RequestPart @RequestParam(value = "fileProgressEntity", required = true) MultipartFile file, HttpServletRequest request) {
        Calendar cal = Calendar.getInstance();
        Integer year = cal.get(Calendar.YEAR);
        Integer month = cal.get(Calendar.MONTH) + 1;
        Integer day = cal.get(Calendar.DAY_OF_MONTH);
        String msg = "SUCCESS";
        String fileName = file.getOriginalFilename();
        //该路径可以从文件中读取，此处演示略
        String filePath = resourcePath + File.separator + year + File.separator + month + File.separator + day + File.separator;
        logger.info("文件保存路径为:{}", filePath);
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            msg = e.getMessage();
        }
        return msg;
    }

    @ResponseBody
    @GetMapping("/status")
    public Object status() {
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        HttpSession session = request.getSession();
        long startTime = System.currentTimeMillis();
        FileProgressEntity fileProgressEntity = (FileProgressEntity) session.getAttribute("fileProgressEntity");
        Assert.notNull(fileProgressEntity, "Error. FileProgressEntity is null");
        long nowTime = System.currentTimeMillis();
        //已传输的时间
        long time = (nowTime - startTime) / 1000 + 1;
        //传输速度 ;单位：byte/秒
        double velocity = ((double) fileProgressEntity.getBytesRead()) / (double) time;
        //估计总时间
        double totalTime = fileProgressEntity.getContentLength() / velocity;
        double estimatedTime = totalTime - time;
        int completed = (int) (100 * (double) fileProgressEntity.getBytesRead() / (double) fileProgressEntity.getContentLength());
        double fileLength = ((double) fileProgressEntity.getBytesRead()) / 1024 / 1024;
        double totalLength = (double) fileProgressEntity.getContentLength() / 1024 / 1024;
        StringBuffer sb = new StringBuffer();
        sb.append(fileProgressEntity + ":" + fileLength + ":" + totalLength + ":" + velocity + ":" + time + ":" + totalTime + ":" + estimatedTime + ":" + fileProgressEntity.getFiles());
        logger.info("上传文件进度，已经完成的百分比{}%:, 已传输时间:{},估计剩余时间:{},已经完成文件数量:{}", completed, time, estimatedTime, fileLength);
        return sb.toString();
    }
}
